package NewTmas.EditMode;

import NewTmas.Graphs.GraphVizGraph;
import taskmaster.auth.User;
import taskmaster.job.JobAllTasksCollection;
import taskmaster.util.LookupLists;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: abhatnag
 * Date: 8/8/11
 * Time: 11:58 AM
 * To change this template use File | Settings | File Templates.
 */
public class AddTaskListener implements ActionListener
{
    LookupLists ll;
    JobAllTasksCollection alltc;
    GraphVizGraph g;

    String jobName;
    Connection con;
    EditIntFrame e;


    public AddTaskListener(String jobName, LookupLists ll, JobAllTasksCollection alltc, GraphVizGraph gp, User user, EditIntFrame e)
    {
        this.ll = ll;
        this.alltc = alltc;
        this.g = gp;
        this.con = user.getConnection();
        this.jobName = jobName;
        this.e = e;


    }

    public void actionPerformed(ActionEvent e)
    {
        JTextField newTaskName = new JTextField();

        int defaultRole = findJobMajorityRole();

        JComboBox roleCbox = new JComboBox();


        HashMap<String, String> rolesHash = new HashMap<String, String>();
        rolesHash.putAll(ll.getAllRolesHash());

        String[] rolNames = new String[rolesHash.size()];

        int i = 0;
        for (Object o : rolesHash.keySet().toArray())
        {
            rolNames[i] = rolesHash.get(o).toString();
            i++;
        }

        for (final String key : rolesHash.keySet())
        {
            final String value = rolesHash.get(key);
            roleCbox.addItem(value);
            // set the default role as selected
            if (key.equalsIgnoreCase(String.valueOf(defaultRole)))
            {
                roleCbox.setSelectedItem(value);
            }
        }

        JComboBox typeCbox = new JComboBox();
        HashMap<String, String> typeHash = new HashMap<String, String>();
        typeHash.putAll(ll.getAllTypesHash());
        for (final String key : typeHash.keySet())
        {
            final String value = typeHash.get(key);
            typeCbox.addItem(value);
        }
        // set selection for the default type: 'S' aka System
        if (typeHash.containsKey("S"))
        {
            typeCbox.setSelectedItem(typeHash.get("S"));
        } else if (typeHash.containsValue("System"))
        {
            typeCbox.setSelectedItem("System");
        }

        JTextField descField = new JTextField();
        JTextField retries = new JTextField();
        JTextField timeout = new JTextField();

        Object message = new Object[]{"Task Tag", newTaskName, "Role", roleCbox, "Type", typeCbox, "Description", descField, "Retries", retries, "Timeout", timeout};

        int input = JOptionPane.showConfirmDialog(null, message, "Select a task to add", JOptionPane.OK_CANCEL_OPTION);

        if (input == JOptionPane.OK_OPTION)
        {

            String role = roleCbox.getSelectedItem().toString();
            String type = typeCbox.getSelectedItem().toString();
            String TaskRole = null, TaskType = null;

            for (Map.Entry<String, String> entry : typeHash.entrySet())
            {
                if (entry.getValue().equalsIgnoreCase(type))
                {
                    TaskType = entry.getKey();
                    break;
                }
            }

            for (Map.Entry<String, String> entry : rolesHash.entrySet())
            {
                if (entry.getValue().equalsIgnoreCase(role))
                {
                    TaskRole = entry.getKey();
                    break;
                }
            }


            addTasktoDB(jobName, descField.getText(), TaskType, TaskRole, retries.getText(), timeout.getText(), newTaskName.getText());
        }

    }

    private int findJobMajorityRole()
    {

        HashMap<Integer, Integer> roleCount = new HashMap<Integer, Integer>();
        for (taskmaster.job.Task t : alltc.alljobTasks)
        {
            if (!roleCount.containsKey(t.getRoleId()))
            {

                roleCount.put(t.getRoleId(), 1);
            } else
            {
                Integer value = roleCount.get(t.getRoleId());
                roleCount.put(t.getRoleId(), value + 1);

            }

        }
        int max = Collections.max(roleCount.values());

        for (Map.Entry<Integer, Integer> entry : roleCount.entrySet())
        {
            if (entry.getValue() == max)
            {
                return entry.getKey();

            }

        }

        return roleCount.get(0);

    }


    private void addTasktoDB(String jobName, String description, String type, String role, String retries, String timeout, String taskTag)
    {

        String command = null;
        if (retries != null && timeout != null)
        {

            command = "INSERT INTO tms.tasks(job_tag,task_tag,description,role_id,type) values('" + jobName + "','" + taskTag + "','" + description + "'," + Integer.valueOf(role) + ",'" + type + "')";
        } else
        {
            command = "INSERT INTO tms.tasks(job_tag,task_tag,description,role_id,type,retries,timeout) values('" + jobName + "','" + taskTag + "','" + description + "'," + Integer.valueOf(role) + ",'" + type + "'," + retries + "," + timeout + ")";

        }
        CallPreparedCommandSQL preparedCommandSQL = new CallPreparedCommandSQL(command, con, g, jobName);

        e.sqlCommands.add(preparedCommandSQL);
        e.model.addElement(preparedCommandSQL.toString());
        e.sqlcommandsList.setModel(e.model);

    }
}
